package org.qiaice.util;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Objects;

@Component
public class OSSUtil {

    // OSS 资源域名
    private static String domain;

    @Value(value = "${oss.domain}")
    private void setDomain(String domain) {
        OSSUtil.domain = domain;
    }

    // OSS 端点
    private static String endpoint;

    @Value(value = "${oss.endpoint}")
    private void setEndpoint(String endpoint) {
        OSSUtil.endpoint = endpoint;
    }

    // Bucket 名称
    private static String bucket;

    @Value(value = "${oss.bucket}")
    private void setBucket(String bucket) {
        OSSUtil.bucket = bucket;
    }

    // Bucket 所在地域
    private static String region;

    @Value(value = "${oss.region}")
    private void setRegion(String region) {
        OSSUtil.region = region;
    }

    // OSSClient 配置构建器
    private static final ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();

    static {
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
    }

    private static OSS ossClient;

    /**
     * 将文件以文件流的形式上传到阿里云对象存储
     * @param inputStream 文件输入流
     * @param fileName 文件在阿里云对象存储中的名称
     * @return 访问文件链接
     */
    public static String upload(InputStream inputStream, String fileName) {
        try {
            // 从环境变量中读取阿里 OSS 访问凭证
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            ossClient = OSSClientBuilder.create()
                    .endpoint(endpoint)
                    .credentialsProvider(credentialsProvider)
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(region)
                    .build();
            ossClient.putObject(new PutObjectRequest(bucket, fileName, inputStream));
        } catch (ClientException e) {
            throw new RuntimeException(e.getErrMsg());
        } catch (OSSException e) {
            throw new RuntimeException(e.getErrorMessage());
        } finally {
            if (Objects.nonNull(ossClient)) {
                ossClient.shutdown();
            }
        }
        return domain + fileName;
    }

    /**
     * 获取文件后缀名
     * @param fileName 文件名
     * @return 文件后缀名
     */
    public static String getFileSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }
}
